import React, { PureComponent } from 'react';
import { connect } from 'react-redux';
import FaceIcon from '@/assets/images/face-icon.png';
import Toast from '@/components/Toast';
import RSAEncrypt from '@/common/rsa-encrypt';
import md5 from 'md5';
import { RouteComponentProps, withRouter } from 'react-router';
import { TXInfoOfType } from '@/store/models/card';
import { getQueryString, loadScript } from '@/common/utils';
import Services from './services';
import './index.less';
import { DOMModal } from '@/components/DOMModal';

interface ILivingInfoProps extends RouteComponentProps {
  history: any;
  TXInfo: TXInfoOfType;
  updateTXInfo: (payload: any) => Promise<any>;
}

interface ILivingInfoState {
  orderId: string;
  enc: string;
  recordId: string;
  isShowIOC: boolean;
}

const oErrorCode = {
  '2': '客户端不支持',
  '3': '无网纹照',
  '4': '用户取消',
  '5': '对比失败(重试超过次数)',
  '6': '超时',
  '7': '其他异常'
};

class LivingInfo extends PureComponent<ILivingInfoProps, ILivingInfoState> {
  constructor(props: ILivingInfoProps) {
    super(props);
    this.state = {
      orderId: '',
      enc: '',
      recordId: getQueryString('recordId'),
      isShowIOC: false
    };
  }

  async componentDidMount() {
    const { certNoEnc, certNameEnc } = this.props.TXInfo;
    // 需要去load加载
    if (!certNoEnc || !certNameEnc)
      this.props.history.replace(`/${window.location.search}`);
    this.setState({
      isShowIOC: true
    });
  }

  loadScriptHook = async () => {
    return await Promise.all([
      loadScript('//m.jr.jd.com/common/jssdk/jrbridge/2.0.9/jrbridge.js'),
      loadScript('//ivep.jd.com/js/jdIvep.1.0.min.js')
    ])
      .then(res => {
        let isLoadedScript = res.filter(i => i === true).length === 2;
        return isLoadedScript;
      })
      .catch(err => {
        return false;
      });
  };

  startFnHook = async () => {
    const { certNoEnc, certNameEnc } = this.props.TXInfo;
    let t = new Date().getTime();
    let certNo = RSAEncrypt.decrypt(certNoEnc);
    let certName = RSAEncrypt.decrypt(certNameEnc);
    let newCertNo = RSAEncrypt.encrypt(certNo);
    let newCertName = RSAEncrypt.encrypt(certName);
    const encStr = md5(`${newCertNo}${newCertName}${t}${RSAEncrypt.MD5KEY}`);
    let params = {
      certNo: newCertNo,
      certName: newCertName,
      t,
      encStr
    };
    let res = await Services.generateAccessToken(params);
    if (res && res.code === 200) {
      let { serialId } = res.data;
      let isLoadedScript = await this.loadScriptHook();
      if (!isLoadedScript) return;
      this.setState(
        {
          isShowIOC: false
        },
        () => {
          if (typeof window['initJdIvep'] == 'undefined') {
            DOMModal.handleOpenModal({
              content: '活体认证发起失败，请重试',
              errorCode: -1
            });
            return;
          }
          try {
            window['initJdIvep'](
              {
                bizId: 'IVEP-JD-FACE-XINYONGGOUJI-SDK', //（必填）
                verifyCode: '800011',
                serialId
              },
              async (obj: any) => {
                let status = obj.getStatus(), //状态
                  serialId = obj.getSerialId(), //流水号，status为1时返回
                  ivepResult = obj.getIvepResult(); //验证结果，status为1时返回
                if (Number(status) === 1) {
                  let t = new Date().getTime();
                  const { phone } = this.props.TXInfo;
                  let phoneNum = RSAEncrypt.encrypt(phone);
                  let encStr = md5(
                    `${serialId}${ivepResult}${phoneNum}${t}${RSAEncrypt.MD5KEY}`
                  );
                  let params = {
                    serialId,
                    ivepResult,
                    phoneNum,
                    t,
                    encStr
                  };
                  let res = await Services.saveLivingCertification(params);
                  if (!res) {
                    this.setState({
                      isShowIOC: true
                    });
                    return;
                  }
                  let { code } = res;
                  if (code === 200) {
                    try {
                      this.props.history.replace(
                        `/videoUpload${window.location.search}`
                      );
                    } catch (e) {
                      console.log('报错了' + e);
                    }
                  } else {
                    Toast.show(`Error code:${code}`, 1);
                    this.setState({
                      isShowIOC: true
                    });
                  }
                } else {
                  let sMsg = oErrorCode[status];
                  if (Number(status) === 2) {
                    Toast.show(sMsg);
                  }
                  this.setState({
                    isShowIOC: true
                  });
                }
              }
            );
          } catch (e) {
            DOMModal.handleOpenModal({
              content: '活体认证发起失败，请重试',
              errorCode: -2
            });
          }
        }
      );
    }
  };

  render() {
    return this.state.isShowIOC ? (
      <div className="living-info">
        <img src={FaceIcon} alt="icon" className="living-info-face-icon" />
        <div className="living-info-content">请正对阳光，确保光线充足</div>
        <div className="confirm-wrapper-btn" onClick={this.startFnHook}>
          开始认证
        </div>
      </div>
    ) : (
      <></>
    );
  }
}

const mapState = ({ CardReSold }: any) => ({
  TXInfo: CardReSold.TXInfo
});

// @ts-ignore
const mapDispath = ({ CardReSold }) => ({
  updateTXInfo: CardReSold.updateTXInfo
});

// @ts-ignore
export default connect(mapState, mapDispath)(withRouter(LivingInfo));
